using System.Collections;
using System.Collections.Generic;
using UnityEngine;

enum ZombieState
{
    Move,
    Eat,
    Die
}
public class Zombie : MonoBehaviour
{
    ZombieState zombieState = ZombieState.Move;
    private Rigidbody2D rgd;
    public float moveSpeed;
    private Animator aim;
    public int Atk = 30;
    public float AtkTime = 2;
    private float AtkTimer = 0;
    private Plant nowPlant;
    public int HP = 100;
    private int NowHP;
    public GameObject ZombieHead;
    void Start()
    {
        rgd = GetComponent<Rigidbody2D>();
        aim = GetComponent<Animator>();
        NowHP = HP;
    }

    // Update is called once per frame
    void Update()
    {
        switch(zombieState)
        {
            case ZombieState.Move:
                MoveUpdate();
                break;
            case ZombieState.Eat:
                EatUpdate();
                break;
            case ZombieState.Die:
                break;
            default:
                break;
        }
    }
    void MoveUpdate()
    {
        rgd.MovePosition(rgd.position + Vector2.left * moveSpeed * Time.deltaTime);
    }
    void EatUpdate()
    {
        AtkTimer += Time.deltaTime;
        if (AtkTimer > AtkTime && nowPlant != null)
        {
            nowPlant.TakeDamage(Atk);
            AtkTimer = 0;
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Plant")
        {
            aim.SetBool("isEating",true);
            ToEat();
            nowPlant = collision.GetComponent<Plant>();
        }
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.tag == "Plant")
        {
            aim.SetBool("isEating", false);
            zombieState = ZombieState.Move;
            nowPlant = null;
        }
    }
    private void ToEat()
    {
        zombieState = ZombieState.Eat;
        AtkTimer = 0;

    }
    public void TakeDamage(int damage)
    {
        if (NowHP <= 0) return;
            this.NowHP -= damage;
        float hp = NowHP * 1f / HP;
        if (NowHP <= 0)
        {
            hp = -1;
        }
        aim.SetFloat("HP", hp);
        if (NowHP <= 0)
        {
            GameObject go = GameObject.Instantiate(ZombieHead, transform.position, Quaternion.identity);
            Destroy(go, 2);
            ZombieDie();
        }
    }
    private void ZombieDie()
    {
        zombieState = ZombieState.Die;
        GetComponent<Collider2D>().enabled = false;
        Destroy(this.gameObject, 2);
    }
}
